package com.gosophia.conferenceManagement.jbpm;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.gosophia.conferenceManagement.ConferenceConfiguration;
import com.gosophia.conferenceManagement.common.entity.ConferenceJobData;
import com.gosophia.taskManagement.entity.Job;
import com.gosophia.taskManagement.entity.JobData;
import com.gosophia.taskManagement.entity.Mission;
import com.gosophia.taskManagement.service.impl.AbstractNodeActionHandler;
import com.gosophia.userManagement.entity.UserInfo;
import com.gosophia.userManagement.service.UserManagementService;

/***
 * 任务创建
 * 
 * @author gaoweiguang
 * 
 */
@Service
@Transactional
public class ConferenceSingleJobActionHandler extends AbstractNodeActionHandler {

	private static final long serialVersionUID = 1L;
	private final Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    @SuppressWarnings("unchecked")
	private HashMap conferenceConfiguration;
    @Autowired
    private UserManagementService userManagementService;
	@Override
	public List<Job> createNewJobsAfterEnteringNode(Mission mission, String nodeName,
			String operationName, JobData jobData) {
		logger.debug("进入【"+nodeName+"】节点");
	    // 任务开始时间
		Date startDate = new Date();
		ConferenceJobData conferenceJobData = (ConferenceJobData)jobData;
		// 任务计划结束时间
		Date scheduleEndDate = mission.getScheduleEndDate();
		NodeConfiguration nodeConfiguration = (NodeConfiguration)conferenceConfiguration.get(nodeName);
		 Assert.notNull(nodeConfiguration);
		 String bsSection=nodeConfiguration.getBsSection();
	 
		List<JobConfiguration> jobConfigurations = nodeConfiguration.getJobConfs();
		 
		 List<Job> jobs = new ArrayList<Job>();
		 for (JobConfiguration jobConf : jobConfigurations) {
		     UserInfo jobSource = getJobSource(mission,conferenceJobData);//任务来源
             UserInfo jobUnderTaker = dynamicJobUnderTaker(mission,bsSection,jobConf,conferenceJobData);//任务承办人
             Job job = createJob(jobConf.getJobType(),//任务类型
		             jobConf.getJobState(),//任务创建后的状态 
		             startDate,//任务开始时间
		                scheduleEndDate, //任务计划结束时间
		                jobUnderTaker, //任务承办人
		                jobSource,//任务来源
		                obtainAfterFinishFlag(nodeConfiguration),
		                jobConf.getDetailURL()
		                         , jobConf.getHandlerURL());
		     jobs.add(job);
		     logger.debug("【"+nodeName+"节点】"+"  actionHandler处理,"+"创建 job jobType：["+ job.getJobType() +"]"
		             +"  job 来自：[id:"+jobSource.getUserInfoId()+",name:"+jobSource.getUserName()
                     +"] job承办人：[id:"+jobUnderTaker.getUserInfoId()+",name:"+jobUnderTaker.getUserName()+"]"
		     );
             }
		    
		// }
//		 if(nodeConfiguration.isGetBackAble()){
//		     //生成一个取回任务
//		     UserInfo jobSource =  getJobSource(mission,conferenceJobData);
//		     UserInfo jobUnderTaker = obtainGetBackJobUnderTaker(mission);
//		     Job getBackAndSubmitJob = createJob(generateGetBackJobType(nodeName,null),//默认使用第一个job的类型+“取回”，例如“申请审批取回”
//		             nodeConfiguration.getJobState(), //使用通用的状态
//		                startDate,//开始时间
//                        scheduleEndDate, //计划结束时间
//                        jobUnderTaker,//任务的承办人
//                        jobSource,//任务来源
//                        obtainAfterFinishFlag(nodeConfiguration), 
//		                 nodeConfiguration.getDetailURL()
//                        , nodeConfiguration.getHandlerURL());
//		     logger.debug("【"+nodeName+"节点】"+"  actionHandler处理,"+"创建 job jobType：["+ getBackAndSubmitJob.getJobType() +"]"
//		             +"  job 来自：[id:"+jobSource.getUserInfoId()+",name:"+jobSource.getUserName()
//		             +"] job承办人：[id:"+jobUnderTaker.getUserInfoId()+",name:"+jobUnderTaker.getUserName()+"]");
//		    jobs.add(getBackAndSubmitJob);
//		 }
		return jobs;
	}

	//此方法暂时能够满足业务需求，可以修正使用动态处理类绑定的方法，处理不同情况下的任务承办人分配
	private UserInfo dynamicJobUnderTaker(Mission mission,String bsSection,JobConfiguration jobConf,ConferenceJobData prejobData){
	    //根据节点，如果是审批节点，就是jobData中的下一个审批人，其他节点统统都是大任务的承办人
	    if(jobConf.isGetBackAble()){//取回的任务
            return obtainConferenceAssignUnderTaker(mission,bsSection);
        }else if (prejobData!=null && prejobData.getNextApproval()!=null){
		      return prejobData.getNextApproval();//审批任务的承办人
		  }
	    else 
	         return obtainConferenceAssignUnderTaker(mission,bsSection);
		  }
		 
	//获取会议申请中指定的会议承办人
	private UserInfo obtainConferenceAssignUnderTaker(Mission mission,String bsSection){
	    Object conf_assign = getCurrentContext().getVariable(ConferenceConfiguration.CONFERENCE_APP_ASSIGN);
	    if(conf_assign!=null && !"会议申请环节".equals(bsSection) ){
	        logger.debug("会议申请环节后的成本人："+(conf_assign));
	        return userManagementService.findUserInfoByUserInfoId((Long)conf_assign);
	    }else{
	        return mission.getUndertaker();
	    }
	}
	
	private String obtainAfterFinishFlag(NodeConfiguration nodeConfig ){
		return  nodeConfig.getJobRelation(); 
	}
	//获取任务来源
	private UserInfo getJobSource(Mission mission,ConferenceJobData jobData){
	    if(jobData==null){
	        return  mission.getCreator();
	    }
	    return jobData.getJob().getOperator();
	}
	
}
